<template>
	<div class="search-suggesstion">
		<van-cell @click="$emit('search', text)" v-for="(text,index) in suggessions" :key="index" icon="search">
			<template #title>
				<div v-html="highlight(text)"></div>
			</template>
		</van-cell>
	</div>
</template>

<script>
	import {
		debounce
	} from 'lodash'
	import {
		getSearchSuggestions
	} from '@/api/search.js'

	export default {
		props: {
			searchText: {
				type: String,
				required: true
			},
		},

		data() {
			return {
				suggessions: [],
			}
		},

		watch: {
			searchText: {
				immediate: true,
				handler: debounce(function(value) {
					this.loadSearchSuggestions(value)
				}, 500)
			}
		},

		methods: {
			async loadSearchSuggestions() {
				try {
					const {
						data: res
					} = await getSearchSuggestions(this.searchText)
					this.suggessions = res.data.options
				} catch (e) {
					this.$toast("数据获取失败")
				}
			},

			highlight(text) {
				const highlightStr = `<span style="color: #3296fa">${this.searchText}</span>`
				const reg = new RegExp(this.searchText, 'gi')
				return text.replace(reg, highlightStr)
			},
		},
	}
</script>

<style lang="less" scoped>

</style>
